package com.glodon.paas.job.util;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glodon.paas.job.exception.JsonConvertException;
import com.glodon.paas.job.exception.JsonException;

public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @SuppressWarnings("rawtypes")
    public static Map jsonToMap(String json) throws JsonException {
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
            throw new JsonException(e);
        }
    }

    public static String mapToJson(Map<?, ?> params) {
        try {
            return objectMapper.writeValueAsString(params);
        } catch (IOException e) {
            throw new JsonConvertException(e);
        }
    }

    public static <T> T jsonToObject(String json, Class<T> type) {
        try {
            return objectMapper.readValue(json, type);
        } catch (IOException e) {
            throw new JsonConvertException(e);
        }
    }

    public static String objectToJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new JsonConvertException(e);
        }
    }
}
